package study.mybatis.support.type;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;

/**
 * https://blog.csdn.net/xiaomojun/article/details/124731190
 * 注册方式
 * （1）<result column=""  typeHandler="" />
 * （2）SqlSessionFactory.setTypeHandlersPackage("")
 * （1）<typeHandler handler="" />
 */
@Slf4j
@MappedJdbcTypes(value = {JdbcType.DATE, JdbcType.TIME, JdbcType.TIMESTAMP})
@MappedTypes(Long.class)
public class Time2LongHandler extends BaseTypeHandler<Long> {

    /**
     * ==================================================
     * 从 Java 类型到 JDBC 类型
     * ==================================================
     */
    //设置非空参数
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long parameter, JdbcType jdbcType) throws SQLException {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>> setNonNullParameter");
        if (jdbcType == JdbcType.DATE) {
            ps.setDate(i, new Date(parameter));
        } else if (jdbcType == JdbcType.TIME) {
            ps.setTime(i, new Time(parameter));
        } else if (jdbcType == JdbcType.TIMESTAMP) {
            ps.setTimestamp(i, new Timestamp(parameter));
        }
    }

    /**
     * ==================================================
     * 从 JDBC 类型到 Java 类型
     * ==================================================
     */
    //获取空结果集（根据列名），一般都是调用这个
    @Override
    public Long getNullableResult(ResultSet rs, String columnName) throws SQLException {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>> setNonNullParameter");
        return toLong(rs.getObject(columnName));
    }

    @Override
    public Long getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>> setNonNullParameter");
        return toLong(rs.getObject(columnIndex));
    }

    @Override
    public Long getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>> setNonNullParameter");
        return toLong(cs.getObject(columnIndex));
    }

    private Long toLong(Object value) {
        if (value instanceof Date) {
            return ((Date) value).getTime();
        } else if (value instanceof Time) {
            return ((Time) value).getTime();
        } else if (value instanceof Timestamp) {
            return ((Timestamp) value).getTime();
        }
        return null;
    }

    public static void main(String[] args) {
       String dd =  DateUtil.date(1687161407000L).toString("yyyy-MM-dd HH:mm:ss");
       log.info("{}", dd);
    }
}
